/*
 * Copyright 2012 Finbudget.com
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package finbudget.client.ui.widget.upload;

import com.google.gwt.http.client.URL;

import finbudget.shared.Constants;

public class Attachment {
	/**
	 * This identifier must be used to store nodes key value in a Record structure
	 * to link attachment to a certain node. In case the Record doesn't contain
	 * value for this field then Record.key is supposed to carry node's key.
	 */
	public final static String keyNodeId = "nodekey";

	private String fileName;
	/**
	 * Blobstore key
	 */
	private String key;

	public Attachment() {
		fileName = null;
		key = null;
	}

	public Attachment(String lineValue) {
		if (lineValue != null) {
			String[] values = lineValue.split(UploadWidget.partsSeparator);
			if (values != null && values.length == 2) {
				key = URL.decodeQueryString(values[0]);
				fileName = URL.decodeQueryString(values[1]);
			} else {
				key = "";
				fileName = "Attachment constructor error: invalid number of split parts (" + (values == null ? "0" : values.length) + ")" + Constants.devError;
			}
		}
	}

	public String getFileName() {
		return fileName;
	}

	public String getBlobKey() {
		return key;
	}

	public void setBlobKey(String key) {
		this.key = key;
	}

	public void setFileName(String name) {
		// File name could contain path info. So remove it before saving
		String file = name;
		if (file != null && file.contains("/")) {
			String[] parts = file.split("/");
			file = parts[parts.length - 1];
		}
		while (file != null && file.contains("\\")) {
			file = file.substring(file.indexOf("\\") + 1);
		}
		this.fileName = file;
	}

	public String getStringValue() {
		if (key != null) {
			return URL.encodeQueryString(key) + UploadWidget.partsSeparator + URL.encodeQueryString(fileName == null ? "Unknown" : fileName);
		}
		return null;

	}
}
